package com.draw.server.bdd_manager;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.draw.core.Color;
import com.draw.server.hibernate.HibernateUtil;
/**
 * Cette classe fourni toutes les méthode permettant aux serveur d'intéragire avec la base de données
 * pour la gestion des Couleurs
 * 
 * @author Damien Tesniere
 *
 */
public class ColorManager {
	private static final Logger logger = LoggerFactory
			.getLogger(ColorManager.class);


	public static List<Color> getAllColor() {
		Session session = HibernateUtil.getSession();
		String req = "from com.draw.core.Color";
		Query query = session.createQuery(req);
		return extractedColors(query);
	}

	private static List<Color> extractedColors(Query query) {
		ArrayList<Color> data = new ArrayList<Color>();
		for (Object obj: query.list() ) {
			data.add((Color) obj);
		}
		return data;
	}
	
	public static int countColor()
	{
		Session session = HibernateUtil.getSession();
		Long res =( (Long) session.createQuery("select count(*) from Color").iterate().next() );
		//System.out.println("\nNB couleur total: "+res.intValue());
		return 	res.intValue();
	}
	
	public static void addColor(Color color){
		logger.info("Creating COLOR : {}", color);
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.save(color);
		tx.commit();
	}
	
}
